<template>
    <el-card class="card">
        <div class="f fac fpj">
            <div class="title">角色管理</div>
            <div class="operation">
                <!-- <el-input class="role-input" suffix-icon="Search" v-model="role_name" placeholder="请输入角色名称" clearable />
                <el-button type="primary" @click="getRoleList(true)">搜索</el-button> -->
                <el-button type="primary" @click="openRoleDialog(1)">新增角色</el-button>
            </div>
        </div>
        <el-table :data="data" :height="tableHeight" stripe class="table">
            <el-table-column prop="id" align="center" label="角色编码" />
            <el-table-column prop="role_name" align="center" label="角色名称" />
            <el-table-column prop="index_page" align="center" label="首页路径" />
            <el-table-column prop="description" align="center" label="描述" />
            <el-table-column prop="status" align="center" label="状态">
                <template #default="scope">
                    <el-tag :type="scope.row.status ? 'success' : 'info'">{{ scope.row.status ? '已启用' : '未启用' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template #default="scope">
                    <!-- :class="[scope.row.id == '10010' ? 'disabled' : '']" -->
                    <span class="table-edit" @click="getPermissionsList(scope.row)">配置权限</span>
                    <span class="table-edit" @click="openRoleDialog(2, scope.row)">编辑</span>
                    <span class="table-delete" @click="deleteRole(scope.row)">删除</span>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination 
            background 
            layout="->, total, prev, pager, next" 
            :pager-count="5"
            v-model:current-page="pageModel.pageNum"
            :page-size="pageModel.pageSize"
            :total="total"
            @current-change="getRoleList()" />
        <el-dialog v-model="showRoleDialog" @close="closeDialog" :close-on-click-modal="false" width="4rem" :title="dialogTitle">
            <el-form :model="form" :rules="rules" hide-required-asterisk ref="refForm">
                <el-form-item label="角色编码" prop="id">
                    <el-input v-model="form.id" :disabled="dialogTitle == '编辑'" min="1" type="number" placeholder="请输入角色编码(100-xx)" />
                </el-form-item>
                <el-form-item label="角色名称" prop="role_name">
                    <el-input v-model="form.role_name" maxlength="12" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="首页路径" prop="index_page">
                    <el-input v-model="form.index_page" placeholder="请输入首页路径" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                    <el-input v-model="form.description" autosize type="textarea" placeholder="请输入描述" />
                </el-form-item>
                <el-form-item label="启/禁用" prop="status" v-if="dialogTitle == '编辑'">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span>
                    <el-button @click="showRoleDialog = false">取消</el-button>
                    <el-button type="primary" @click="submit">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-drawer
            v-model="drawerShow"
            title="权限配置"
            direction="rtl">
            <div class="menu-tree">
                <div class="tree">
                    <el-tree :data="menuTree" :default-expanded-keys="defaultExpandedKeys" @check="chooseCheckMenu" node-key="id" :default-checked-keys="checkMenu" show-checkbox :props="props" />
                </div>
                <div class="footer">
                    <el-button type="primary" @click="setRoleermission">确定</el-button>
                    <el-button @click="drawerShow = false">取消</el-button>
                </div>
            </div>
        </el-drawer>
    </el-card>
</template>

<script setup>
    import { ref, onMounted, watchEffect, reactive } from 'vue'
    import http from '@/api/home'
    import utils from '@/utils/utils'

    let role_name = ref('')
    let total = ref(0)
    let tableHeight = ref('')
    const pageModel = ref({
        pageNum: 1,
        pageSize: 20
    })
    const data = ref([])
    let showRoleDialog = ref(false)
    let dialogTitle = ref('')
    const form = reactive({
        id: '',
        role_name: '',
        index_page: '',
        description: '',
        status: 1
    })
    const refForm = ref()
    const rules = {
        id: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
        role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        index_page: [{ required: true, message: '请输入首页路径', trigger: 'blur' }]
    }
    let drawerShow = ref(false)
    const menuTree = ref([])
    const defaultExpandedKeys = []
    const props = {
        children: 'children',
        label: 'name',
    }
    const checkMenu = ref([])
    const checkParentMenu = ref([])
    let currentSettingID = ref('')

    const setTableHeight = () => {
        let tableH = 320 // 距离下方的距离 
        let tableHeightDetail = window.innerHeight - tableH
        if (tableHeightDetail <= 400) {
            tableHeight.value = 400
        } else {
            tableHeight.value = window.innerHeight - tableH 
        }
    }
    watchEffect(() => setTableHeight())

    onMounted(() => {
        getRoleList()
    })

    // 获取权限菜单
    const getPermissionsList = (row) => {
        drawerShow.value = true
        currentSettingID.value = row.id
        http.permissionList({id: row.id}).then(res => {
            menuTree.value = res.data
            checkMenu.value = utils.flatten(res.data).filter(item => item.status == 1).map(item => item.id)
            // 默认展开的数据 
            menuTree.value.forEach(item => {
                if (item.children && item.children.length > 0) {
                    defaultExpandedKeys.push(item.id)
                }
            })
        })
    }
    
    // 选中的菜单节点数组
    const chooseCheckMenu = (checkObj, checkKeys) => {
        checkMenu.value = checkKeys.checkedKeys
        // 这不能将父级节点推入数组，否则就不能选择，在提交的时候再推入
        // checkMenu.value = [...checkMenu.value, ...checkParentMenu.value]
        checkParentMenu.value = checkKeys.halfCheckedKeys
        
    }
    // 设置角色权限 
    const setRoleermission = () => {
        checkMenu.value = [...checkMenu.value, ...checkParentMenu.value]
        http.setPermission({
            id: currentSettingID.value,
            menu_ids: JSON.stringify(checkMenu.value)
        }).then(res => {
            ElMessage({ type: 'success', message: res.message })
            drawerShow.value = false
        })
    }

    // 获取角色列表
    const getRoleList = (resetPageNum = false) => {
        if (resetPageNum) {
            pageModel.value.pageNum = 1
        }
        http.roleList({
            role_name: role_name.value,
            ...pageModel.value
        }).then(res => {
            data.value = res.data.records
            total.value = res.data.total
        })
    }

    // 打开对话框
    const openRoleDialog = (value, data) => {
        showRoleDialog.value = true
        // 新增
        if (value == 1) {
            dialogTitle.value = '新增'
            return
        } else {
            dialogTitle.value = '编辑'
            form.id = data.id
            form.role_name = data.role_name
            form.description = data.description
            form.status = data.status,
            form.index_page = data.index_page
        }
    }

    //提交
    const submit = () => {
        refForm.value.validate((valid) => {
            if (valid) {
                if (dialogTitle.value == '新增') {
                    http.roleAdd(form).then(res => {
                        ElMessage({ type: 'success', message: res.message })
                        showRoleDialog.value = false
                        getRoleList()
                    })
                } else {
                    http.roleUpdate(form).then(res => {
                        ElMessage({ type: 'success', message: res.message })
                        showRoleDialog.value = false
                        getRoleList()
                    })
                }
            }
        })
    }

    // 删除角色
    const deleteRole = (data) => {
        ElMessageBox.confirm(
            '是否删除该角色?',
            '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            http.roleDelete({id: data.id}).then(res => {
                ElMessage({ type: 'success', message: res.message })
                getRoleList()
            })
        })
    }

    // 关闭对话框
    const closeDialog = () => {
        refForm.value.resetFields()
        clearObj(form)
    }
    const clearObj = (obj) => {
        const empty = {}
        for (const key in obj) {
            empty[key] = ''
        }
        Object.assign(obj, empty)
    }
</script>

<style lang="scss" scoped>
.card {
    box-shadow: 0px 1px 4px 0px rgba(0,0,0,0.2);
    margin-top: 0.14rem;
    height: calc(100vh - 0.68rem - 0.7rem);
    .title {
        font-size: 0.2rem;
        font-weight: bold;
        color: #000;
        padding-bottom: 0.1rem;
        border-bottom: 4px solid $ncpColor;
    }
    .role-input {
        width: 2rem;
        margin-right: 0.2rem;
    }
    .table {
        width: 100%; 
        margin: 0.1rem 0; 
        margin-bottom: 0.3rem;
    }
    .table-edit {
        color: $otherColor;
        margin-right: 0.2rem;
        cursor: pointer;
        &:hover {
            text-decoration: underline;
        }
    }
    .disabled {
        pointer-events: none;
        opacity: 0.8;
    }
    .table-delete {
        color: $helpColor;
        cursor: pointer;
        &:hover {
            text-decoration: underline;
        }
    }
    :deep(.el-drawer__title) {
        font-size: 0.16rem;
    }
    .menu-tree {
        height: 100%;
        position: relative;
        .tree {
            height: calc(100% - 0.4rem);
            overflow-y: auto;
        }
        .footer {
            position: absolute;
            bottom: 0;
            left: 0;
        }
    }
    
}
</style>